<template>
  <div>
    <a-form-model
      ref="formModel"
      :model="form"
      layout="inline"
      class="search-form"
      :rules="formRules"
    >
      <div class="search-box">
        <a-form-model-item class="search-item" prop="name" label="维护人员">
          <a-input
            autocomplete="off"
            v-model="form.name"
          ></a-input>
        </a-form-model-item>
        <a-form-model-item
          class="search-item"
          prop="resultType"
          label="事件结果"
        >
          <a-select
            :getPopupContainer="
                triggerNode => {
                  return triggerNode.parentNode || document.body;
                }"
            v-model="form.resultType">
            <a-select-option value="">全部</a-select-option>
            <a-select-option value="1">成功</a-select-option>
            <a-select-option value="0">失败</a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item class="search-item" prop="ip" label="IP">
          <a-input
            autocomplete="off"
            v-model="form.ip"
          ></a-input>
        </a-form-model-item>
        <a-form-model-item class="search-item" prop="type" label="操作类型">
          <a-select
            :getPopupContainer="
                triggerNode => {
                  return triggerNode.parentNode || document.body;
                }"
            v-model="form.type">
            <a-select-option
              v-for="(d, i) in actionTypeMap"
              :key="d.key + '_' + i"
              :value="d.key"
              >{{ d.label }}</a-select-option
            >
          </a-select>
        </a-form-model-item>
        <a-form-model-item class="search-item" prop="sortType" label="排序">
          <a-select
            :getPopupContainer="
                triggerNode => {
                  return triggerNode.parentNode || document.body;
                }"
            v-model="form.sortType">
            <a-select-option
              v-for="(d, i) in sortMap"
              :key="i"
              :value="d.value"
            >
              {{ d.name }}
            </a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item
          class="search-item"
          prop="dateRange"
          label="请求时间"
        >
          <a-range-picker
            v-model="form.dateRange"
            inputReadOnly
            :placeholder="['开始时间', '结束时间']"
            :disabled-date="disabledDate"
            format="YYYY/MM/DD HH:mm:ss"
            :show-time="true"
          />
        </a-form-model-item>
        <div class="search-item btn-wrapper">
          <a-button
            type="primary"
            @click="loadData(true)"
            icon="search"
            style="margin-left: 12px"
          >
            查询
          </a-button>
          <a-button
            @click="resetSearchForm"
            icon="reload"
            style="margin-left: 12px"
          >
            重置
          </a-button>
          <a-button
            v-if="hasPermission('SysLogResume')"
            type="primary"
            @click="handleLogOperation('resume')"
            style="margin-left: 24px"
          >
            恢复
          </a-button>
          <a-button
            v-if="hasPermission('sysLogBackup')"
            type="primary"
            @click="handleLogOperation('backup')"
            style="margin-left: 12px"
          >
            备份
          </a-button>
          <div
            v-if="isBussinessLog && hasPermission('SysLogDelete')"
            style="display: inline-block; margin-left: 24px"
          >
            <a-popconfirm
              title="确定删除吗?"
              @confirm="() => handleLogOperation('deleteLogs')"
            >
              <a-button type="primary">删除</a-button>
            </a-popconfirm>
            <div style="color: rgba(0, 0, 0, 0.45); line-height: 16px">
              只删除六个月之前的业务日志
            </div>
          </div>
        </div>
      </div>
    </a-form-model>

    <a-table
      ref="table"
      rowKey="id"
      size="middle"
      :columns="columns"
      :dataSource="gDataSource"
      :pagination="gPagination"
      @change="gHandleTableChange"
    >
      <span slot="sortCol" slot-scope="text, record, index">
        {{
          (gPagination.current - 1) * gPagination.pageSize + parseInt(index) + 1
        }}
      </span>
      <a-tooltip
        slot="logContent"
        slot-scope="text"
        placement="topLeft"
        :title="text"
      >
        <span>{{ text }}</span>
      </a-tooltip>
    </a-table>
  </div>
</template>

<script>
import moment from "moment";
import { GwListMixin } from "@/mixins/GwListMixin";
import { getAction } from "@/api/manage";
import { hasRight } from "@/utils/util";

export default {
  name: "Log",
  mixins: [GwListMixin],
  props: {
    modelType: {
      type: String,
      default: "",
    },
  },
  data() {
    return {
      // 表头
      columns: [
        {
          title: "序号",
          dataIndex: "",
          key: "rowIndex",
          width: 50,
          align: "center",
          scopedSlots: { customRender: "sortCol" },
        },
        {
          title: "请求时间",
          dataIndex: "createTime",
          width: 100,
        },
        {
          title: "维护人员",
          dataIndex: "username",
          width: 50,
        },
        {
          title: "IP",
          dataIndex: "ip",
          width: 80,
        },
        {
          title: "事件类型",
          dataIndex: "type",
          width: 50,
          customRender: (text) => (this.isBussinessLog ? "业务" : "系统"),
        },
        {
          title: "日志内容",
          dataIndex: "logContent",
          ellipsis: true,
          scopedSlots: { customRender: "logContent" },
          width: 200,
        },
        {
          title: "操作类型",
          dataIndex: "operateTypeName",
          width: 50,
        },
        {
          title: "事件结果",
          dataIndex: "statusName",
          width: 50,
        },
      ],
      formRules: {
        name: [
          {
            validator: this.validators.noWhitespace(),
            trigger: "change",
          },
          {
            validator: this.validators.noIllegalString(),
            trigger: "change",
          },
          {
            max: 10,
            message: "长度在 1 到 10 个字符",
            trigger: "change",
          },
        ],
        logContent: [
          {
            validator: this.validators.noWhitespace(),
            trigger: "change",
          },
          {
            validator: this.validators.noIllegalString(),
            trigger: "change",
          },
          {
            max: 20,
            message: "长度在 1 到 20 个字符",
            trigger: "change",
          },
        ],
        ip: [
          {
            validator: this.validators.noWhitespace(),
            validator: this.validators.isValidIp(),
            trigger: "change",
          },
        ],
        dateRange: [{ validator: this.validators.datetimeValidator() }],
      },
      resultMap: ["全部", "成功", "失败"],
      actionTypeMap: [{ key: "", label: "全部" }],
      sortMap: [
        {
          name: "时间降序",
          value: 0,
        },
        {
          name: "时间升序",
          value: 1,
        },
        // {
        //   name: "IP降序",
        //   value: 2
        // },
        // {
        //   name: "IP升序",
        //   value: 3
        // },
        {
          name: "用户名降序",
          value: 4,
        },
        {
          name: "用户名升序",
          value: 5,
        },
        {
          name: "操作类型降序",
          value: 6,
        },
        {
          name: "操作类型升序",
          value: 7,
        },
      ],
      form: {
        dateRange: [],
        name: "",
        logContent: "",
        ip: "",
        type: "",
        resultType: "",
        sortType: 0,
      },
      isBussinessLog: false,
      systemLogOperateType: [
        "9",
        "10",
        "12",
        "13",
        "20",
        "21",
        "22",
        "23",
        "27",
      ],
    };
  },
  mounted() {
    this.isBussinessLog = this.modelType === "businessLog";
    if (this.isBussinessLog) {
      this.gQueryParam.excludeOperateType = [
        "5",
        "6",
        "7",
        "8",
        "9",
        "10",
        "11",
        "12",
        "13",
        "14",
        "15",
        "16",
        "17",
        "18",
        "19",
        "20",
        "21",
        "22",
        "23",
        "24",
        "25",
        "27",
      ];
      this.gQueryParam.title = "业务日志";
    } else {
      this.gQueryParam.excludeOperateType = "";
      this.gQueryParam.title = "系统日志";
    }
    this.loadData();
    this.loadActionTypeList();
  },
  methods: {
    hasPermission(code) {
      return hasRight(code);
    },
    disabledDate(current) {
      return current && current > moment().endOf("day");
    },
    loadData(isDoSearch) {
      if (this.form.type !== "") {
        this.gQueryParam.operateType = [this.form.type];
      } else if (this.isBussinessLog) {
        this.gQueryParam.operateType = "";
      } else {
        this.gQueryParam.operateType = this.systemLogOperateType;
      }
      this.gQueryParam.username = this.form.name;
      this.gQueryParam.ip = this.form.ip;
      this.gQueryParam.logContent = this.form.logContent;
      this.gQueryParam.status = this.form.resultType;
      this.gQueryParam.orderType = this.form.sortType;
      this.gQueryParam.startTime =
        this.form.dateRange.length > 0
          ? this.form.dateRange[0].format("YYYY/MM/DD HH:mm:ss")
          : "";
      this.gQueryParam.endTime =
        this.form.dateRange.length > 0
          ? this.form.dateRange[1].format("YYYY/MM/DD HH:mm:ss")
          : "";
      this.$refs.formModel.validate((error) => {
        if (!error) {
          return;
        }
        if (isDoSearch) {
          this.gQueryParam.pageNo = 1;
          this.gPagination.current = 1;
        }
        getAction("/sys/log/list", this.gQueryParam).then((res) => {
          if (res.success) {
            this.gDataSource = res.result.records;
            this.gPagination.total = res.result.total;
          }
        });
      });
    },
    loadActionTypeList() {
      this.actionTypeMap = [{ key: "", label: "全部" }];
      const postData = {};

      if (this.isBussinessLog) {
        postData.isSystem = false;
        postData.excludeOperateType = this.gQueryParam.excludeOperateType;
      } else {
        postData.isSystem = true;
        postData.excludeOperateType = "";
      }

      getAction("/sys/log/operate_type_list", postData).then((res) => {
        if (res.success) {
          this.actionTypeMap = this.actionTypeMap.concat(
            res.result.map((item) => {
              return {
                key: item.value,
                label: item.name,
              };
            })
          );
        }
      });
    },
    handleLogOperation(operate) {
      if (this.isBussinessLog) {
        this.gQueryParam.operateType = "";
      } else {
        this.gQueryParam.operateType = this.systemLogOperateType;
      }
      this.gQueryParam.orderType = 1;
      getAction("/sys/log/" + operate, this.gQueryParam).then((res) => {
        if (res.success) {
          this.$message.success("操作成功");
          if (operate === "deleteLogs") {
            this.resetSearchForm();
            this.loadData(true);
          }
        }
      });
    },
    resetSearchForm() {
      this.form.dateRange = [];
      this.form.name = "";
      this.form.logContent = "";
      this.form.ip = "";
      this.form.type = "";
      this.form.resultType = "";
      this.form.sortType = 0;
      this.$refs.formModel.resetFields();
    },
  },
};
</script>

<style
  lang="less"
  scoped
>
.search-form {
  margin-bottom: 18px;
  display: block;

  /deep/ .ant-form-item .ant-form-item-label {
    min-width: 80px;
  }

  /deep/ .ant-form-item-control-wrapper {
    min-width: 184px;
  }
  /* .flex-reverse{
      display: flex;
      flex-direction: column-reverse;
    } */
  .search-box {
    display: flex;
    justify-content: flex-start;
    align-items: center;
    flex-wrap: wrap;
    .search-item {
      padding: 0 22px 6px 0;
      min-width: 360px;
    }
    .btn-wrapper {
      display: flex;
      position: relative;
    }
  }
  /deep/ .ant-form-inline .ant-form-item {
    margin: 0;
  }
}

.search-tool-row {
  display: flex;
  justify-content: flex-start;

  &:first-child {
    margin-bottom: 14px;
  }
}
</style>